package com.sf.dlb.controller;

import com.sf.dlb.bean.NewClassRquestBean;
import com.sf.dlb.bean.NewRquestBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.TokenEntity;
import com.sf.dlb.service.*;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 新闻阅读
 *
 * Created by tanjing on 2018/12/19.
 */
@RestController
@RequestMapping(value = "/v1/new")
public class NewController extends BaseController{

    @Autowired
    private NewListService newListService;
    @Autowired
    private NewClassService newClassService;
    @Autowired
    private NewRecodService newRecodService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private VisitorRecordService visitorRecordService;
    @Autowired
    private VisitorInfoService visitorInfoService;

    /**
     * 获取新闻列表
     * @param request
     * @param newRquestBean
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Object newList(HttpServletRequest request,@RequestBody NewRquestBean newRquestBean){
        String token=request.getHeader(global.token_request_header_key);
        ResultVO resultVO;
        //判断参数是否合法
        logger.info("newList request json === " + GsonUtils.getInstance().toJson(newRquestBean));
        if(StringUtils.isEmpty(newRquestBean.getClassId())){
            newRquestBean.setClassId("1");//默认是热点
        }
        if(newRquestBean.getCurrentPages()!=0){
            newRquestBean.setCurrentPages(newRquestBean.getCurrentPages()-1);//JPA,从0开始算；
        }
        if(newRquestBean.getPageSize()==0){
            newRquestBean.setPageSize(20);//默认20条
        }
        if(StringUtils.isBlank(token)||StringUtils.contains(token,global.user_visitor_token_prefix)){
            resultVO =newListService.findbyListNotLogin(newRquestBean);
        }else{
            resultVO=userInfoService.getTokenChekout(request);
            if(resultVO.getCode().intValue()==200){
                TokenEntity tokenEntity = (TokenEntity) resultVO.getData();
                newRquestBean.setUserId(tokenEntity.getUserId());
                resultVO = newListService.findbyList(newRquestBean);
            }
        }
        logger.info("newList response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }

    /**
     * 获取新闻正文
     * @param request
     * @param newId
     * @return
     */
    @RequestMapping(value = "/info/{newId}",method = RequestMethod.GET)
    @ResponseBody
    public Object newInfo(HttpServletRequest request, @PathVariable String newId){
        String token=request.getHeader(global.token_request_header_key);
        ResultVO resultVO;
        //判断参数是否合法
        logger.info("newInfo request json === " + newId);
        if(StringUtils.isEmpty(newId)){
            return ResultVOUtil.error(ResponseConstant.ERROR,"新闻id不能为空");
        }
        if(StringUtils.isBlank(token)||StringUtils.contains(token,global.user_visitor_token_prefix)){
            resultVO=newListService.findByNewInfoNotLogin(newId);
        }else{
            resultVO=userInfoService.getTokenChekout(request);
            if(resultVO.getCode().intValue()==200){
                TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
                resultVO=newListService.findByNewInfo(tokenEntity.getUserId(),newId);
            }
        }
        logger.info("newInfo response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 获取新闻所有分类
     * @param request
     * @return
     */
    @RequestMapping(value = "/class",method = RequestMethod.GET)
    @ResponseBody
    public Object newClass(HttpServletRequest request){
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
        resultVO=newClassService.findByAll(tokenEntity.getUserId());
        logger.info("newClass response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 获取用户订阅的分类
     * @param request
     * @return
     */
    @RequestMapping(value = "/userSubClass",method = RequestMethod.GET)
    @ResponseBody
    public Object userSubClass(HttpServletRequest request){
        String token=request.getHeader(global.token_request_header_key);
        ResultVO resultVO;
        if(StringUtils.isBlank(token)||StringUtils.contains(token,global.user_visitor_token_prefix)){
            resultVO=newClassService.findByUserSubClass();
        }else{
            resultVO=userInfoService.getTokenChekout(request);
            if(resultVO.getCode().intValue()==200){
                TokenEntity tokenEntity = (TokenEntity) resultVO.getData();
                resultVO = newClassService.findByUserSubClass(tokenEntity.getUserId());
            }
        }
        logger.info("userSubClass response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 用户订阅分类
     * @param request
     * @return
     */
    @RequestMapping(value = "/addClassSub",method = RequestMethod.POST)
    @ResponseBody
    public Object addClassSub(HttpServletRequest request,@RequestBody NewClassRquestBean newClassRquestBean){
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        TokenEntity tokenEntity=(TokenEntity)resultVO.getData();
        if(null==newClassRquestBean.getClassIds()){
            return ResultVOUtil.error(ResponseConstant.ERROR,"缺少订阅数据");
        }
        resultVO=newClassService.addClassSub(tokenEntity.getUserId(),newClassRquestBean.getClassIds());
        logger.info("addClassSub response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 新闻阅读
     * @param request
     * @return
     */
    @RequestMapping(value = "/read",method = RequestMethod.POST)
    @ResponseBody
    public Object newRead(HttpServletRequest request,@RequestBody NewRquestBean newRquestBean){
//        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        String token=request.getHeader(global.token_request_header_key);
        //判断参数是否合法
        logger.info("newRead request json === " + GsonUtils.getInstance().toJson(newRquestBean));
        if(StringUtils.isEmpty(newRquestBean.getNewId())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"新闻id不能为空");
        }
        if(StringUtils.isEmpty(newRquestBean.getStartTime())&&StringUtils.isEmpty(newRquestBean.getEndTime())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"阅读时间不能为空");
        }
        if(StringUtils.isNotBlank(newRquestBean.getStartTime())&&StringUtils.isNotBlank(newRquestBean.getEndTime())){
            return ResultVOUtil.error(ResponseConstant.ERROR,"开始时间与结束时间不能同时传输");
        }
        ResultVO resultVO;
        if(StringUtils.isBlank(token)||StringUtils.contains(token,global.user_visitor_token_prefix)) {
            resultVO=visitorInfoService.getTokenChekout(request);
            if(resultVO.getCode().intValue()!=200) {
                return resultVO;
            }
            TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
            newRquestBean.setUserId(tokenEntity.getUserId());
            if(StringUtils.isNotBlank(newRquestBean.getStartTime())){
                resultVO = visitorRecordService.startReadNew(newRquestBean);
            }else if(StringUtils.isNotBlank(newRquestBean.getEndTime())){
                resultVO = visitorRecordService.endReadNew(newRquestBean);
            }
        }else{
            resultVO=userInfoService.getTokenChekout(request);
            if(resultVO.getCode().intValue()!=200) {
                return resultVO;
            }
            TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
            newRquestBean.setUserId(tokenEntity.getUserId());
            if(StringUtils.isNotBlank(newRquestBean.getStartTime())){
                //开始阅读
                resultVO = newRecodService.startReadNew(newRquestBean);
            }else if(StringUtils.isNotBlank(newRquestBean.getEndTime())){
                //结束阅读
                if(StringUtils.isEmpty(newRquestBean.getSlideNumber())){
                    return ResultVOUtil.error(ResponseConstant.ERROR,"滑动不能为空");
                }
                if(newRquestBean.getSlideNumber().indexOf("&")<0){
                    return ResultVOUtil.error(ResponseConstant.ERROR,"滑动参数不合法");
                }
                resultVO = newRecodService.endReadNew(newRquestBean);
            }
        }
        logger.info("newRead response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }

    /**
     * 4.13.	新闻领取dlb（加密）
     * @param request
     * @param newRquestBean
     * @return
     */
    @RequestMapping(value = "/getdlb",method = RequestMethod.POST)
    @ResponseBody
    public Object newGetdlb(HttpServletRequest request,@RequestBody NewRquestBean newRquestBean){
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        //判断参数是否合法
        if (null==newRquestBean) {
            return ResultVOUtil.error(ResponseConstant.ERROR, "参数不合法");
        }
        //获取用户userId
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        //只去掉逻辑，接口保留，看看修改逻辑之后，还有多少机器人在访问此接口；
//        newRquestBean.setUserId(tokenEntity.getUserId());
//        resultVO=newRecodService.getDlb(newRquestBean);
        logger.info("newGetdlb response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }

}
